package com.example.ai.model.source

import android.util.Log
import com.example.ai.Config
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener

/**
 * Created by lijinxi on 2024/3/9.
 * @Description:
 */
class WSSource() {
    companion object {
        const val BASE_URL = "https://workspace-wsbb56b05d5f82b404-http-8888.ide.byted.org/ws"
    }

    private val request = Request.Builder().url(BASE_URL).build()
    private val client = OkHttpClient()
    private lateinit var webSocket: WebSocket

    fun setWebSocketListener(listener: WebSocketListener) {
        try {
            if (Config.DEBUG.not()) {
                webSocket = client.newWebSocket(request, listener)
            }
        } catch (e: retrofit2.HttpException) {
            Log.e(this::class.java.simpleName, "网络错误", Throwable(e))
        }
    }

    fun closeWebSocket() {
        if (Config.DEBUG.not()) {
            webSocket.cancel()
            webSocket.close(1000, "normal close")
        }
    }

    fun sendMessage(text: String) {
        if (Config.DEBUG.not()) {
            webSocket.send(text)
        }
    }
}